<template>
  <div class="container">
    <el-row  >
      <el-col :span="12">
        <strong style="color: #00b050; font-size: 22px;padding-right: 5px">①</strong>
        <el-button  @click="download" type="success"  >下载导入模板</el-button>
        <el-button  @click="close" >关闭</el-button>

        <h5><strong style="color: #00b050; font-size: 22px;padding-right: 5px">②</strong>请选择数据文件</h5>
        <FortenUpload
          :fileRefTable="'tmp'"
          :fileSavePath="'tmp/import'"
          :fileType="'import'"
          :fileRefId="viewKey"
          :fileMaxNum="1"
          :autoLoadFile="false"
          :noTitle="true"
          :showLastFile="true"
          @upload-success="uploadSuccess"
          @remove-success="removeSuccess"
          ref="fileUpload"
        ></FortenUpload>

        <h5>最近上传的文件</h5>
        <FortenUpload
          :fileRefTable="'tmp'"
          :fileSavePath="'tmp/import'"
          :fileType="'import'"
          :fileRefId="viewKey"
          :fileMaxNum="1"
          :noTitle="true"
          :isOneLineFull="true"
          :isShowDate="true"
          :isReverseData="true"
          :listHeight="'25px'"
          :readonly="true"  :isOneLine="true"
          style="max-height: 400px;overflow: auto; text-align: left"
          ref="fileHistory"
        ></FortenUpload>
      </el-col>
      <el-col :span="12">
        <h5>操作结果</h5>
        <div v-html="strings.defaultString(importMsg,'无')" style=" max-height: calc(100vh - 100px);overflow: auto;"></div>
      </el-col>
    </el-row>


    <data-view  ref="dataview" :propViewKey="viewKey" :propPageSize="10" :propAutoFetchData="false"
                :propShowToolBar="false"
                :propOnlyQuery2="true"
                :propCustomCols="myPropCustomCols"
                style="display: none"
    >
      <template #importResult="{field,value,row}" >
        <div
          v-html="utils.getDictLabel(row.importResult, 'import_result', '')"
        ></div>
      </template>
      <template #importStamp="{field,value,row}" >
        {{row.importStamp}}
      </template>
      <template #importRemark="{field,value,row}" >
        <el-tooltip class="item" effect="dark" :content="row.importRemark" placement="left">
          <div> {{row.importRemark}}</div>
        </el-tooltip>

      </template>
    </data-view>
    <!--<el-row>
      <el-col :span="6" >
        <el-row  >
          <el-col :span="24">
            <strong style="color: #00b050; font-size: 22px;padding-right: 5px">①</strong>
            <el-button  @click="download" type="success"  >下载导入模板</el-button>
          </el-col>
        </el-row>

        <h5><strong style="color: #00b050; font-size: 22px;padding-right: 5px">②</strong>请选择数据文件</h5>
        <FortenUpload
          :fileRefTable="'tmp'"
          :fileSavePath="'tmp/import'"
          :fileType="'import'"
          :fileRefId="viewKey"
          :fileMaxNum="1"
          :autoLoadFile="false"
          :noTitle="true"
          :showLastFile="true"
          @upload-success="uploadSuccess"
          @remove-success="removeSuccess"
          ref="fileUpload"
        ></FortenUpload>

        <el-row  >
          <el-col :span="24">
            <strong style="color: #00b050; font-size: 22px; padding: 0 5px">③</strong>
            <el-button  @click="execImport" type="danger" :disabled="strings.isBlank(importStamp)" >导入数据</el-button>
            <el-button  @click="close" >关闭</el-button>
          </el-col>
        </el-row>
        <el-row  >
          <el-col :span="24">
            <h5>操作结果：{{strings.defaultString(importMsg,'无')}}</h5>
          </el-col>
        </el-row>

        <h5>最近上传的文件</h5>
        <FortenUpload
          :fileRefTable="'tmp'"
          :fileSavePath="'tmp/import'"
          :fileType="'import'"
          :fileRefId="viewKey"
          :fileMaxNum="1"
          :noTitle="true"
          :isOneLineFull="true"
          :isShowDate="true"
          :isReverseData="true"
          :listHeight="'25px'"
          :readonly="true"  :isOneLine="true"
          style="max-height: 400px;overflow: auto; text-align: left"
          ref="fileHistory"
        ></FortenUpload>

      </el-col>
      <el-col :span="18">
        <data-view  ref="dataview" :propViewKey="viewKey" :propPageSize="10" :propAutoFetchData="false"
        :propShowToolBar="false"
        :propOnlyQuery2="true"
        :propCustomCols="myPropCustomCols"
        >
          <template #importResult="{field,value,row}" >
            <div
              v-html="utils.getDictLabel(row.importResult, 'import_result', '')"
            ></div>
          </template>
          <template #importStamp="{field,value,row}" >
            {{row.importStamp}}
          </template>
          <template #importRemark="{field,value,row}" >
            <el-tooltip class="item" effect="dark" :content="row.importRemark" placement="left">
             <div> {{row.importRemark}}</div>
            </el-tooltip>

          </template>
        </data-view>
      </el-col>
    </el-row>-->
  </div>
</template>

<script>
/*eslint-disable*/
import FortenUpload from '@/components/common/FortenUpload.vue'
export default {
  name: 'FortenImport',
  components: {FortenUpload},
  props: ['param'],
  mounted() {
  },
  data() {
    return {
      viewKey: null,
      filePath: null,
      importMsg: null,
      importStamp: null,
      opType: 1,
      importDataCheckType: [
        { value: 'require', label: '必须的(不可以为空，同时数字不可以为0)' },
        { value: 'number1', label: '正整数(必须为大于0的整数)' },
        { value: 'number2', label: '正数(必须为大于0的正数)' },
        { value: 'enum1', label: '枚举：0、1、是、否' },
        { value: 'date1', label: '日期(年-月-日)，可以为空' },
        { value: 'date2', label: '日期(年-月-日)，不可以为空' },
        { value: 'date3', label: '日期(年-月-日 时:分:秒)，可以为空' },
        { value: 'date4', label: '日期(年-月-日 时:分:秒)，不可以为空' }
      ]
    }
  },
  methods: {
    //关闭窗口
    close(){
      this.$emit("printFormClose")
    },
    //下载导入模板
    download(){
      this.utilVue.loadShow(true)
      let exportEntry = this.$refs.dataview.listEntry
      let viewName = this.$refs.dataview.viewName
      let columns = this.$refs.dataview.columns
      let columnsNew = [],columnsNew2=[]
      columns.forEach(column => {
        //排除临时表的4个字段
        if (['id','importStamp','importResult','importRemark'].includes(column.name)) return true
        let titleOld = column.title
        let columnNew = JSON.parse(JSON.stringify(column))
        let columnNew2 = JSON.parse(JSON.stringify(column))
        columnNew.field = columnNew.name
        columnNew.title = columnNew.title
        columnNew.isRequired = false
        if (columnNew.rule && columnNew.rule.findIndex(tmp => tmp.key == 'require') != -1) {
          columnNew.isRequired = true
        }

        columnNew2.field = columnNew2.name
        columnNew2.title = columnNew2.title
        let title = '无特殊校验'
        if (columnNew.importDataCheckType) {
          title = this.importDataCheckType.filter(type => type.value == columnNew.importDataCheckType ).map(tmp => {
            return tmp.label
          }).join('#')
        }

        columnNew.title = titleOld + '#' + title
        columnsNew.push(columnNew)

        columnNew2.title = title
        console.log('columnNew', columnNew)
        console.log('title', title)
        columnsNew2.push(columnNew2)

      })


      let params = {
        filename: viewName+'_'+new Date().format('yyyyMMdd'),
        sheetName: viewName,
        isHeader: true,
        listEntry: exportEntry,
        fields: this.utilVue.json2str(columnsNew)
      }
      //if (columnsNew2.length > 0) params.fields2 = this.utilVue.json2str(columnsNew2)

      this.$ajax.post('/tool/exportTemplate', params).then(resp => {
        this.utilMessage.success('导出成功，开始下载')
        global.utils.downloadrRes(resp.data)
        setTimeout(() => {
          this.utilVue.loadHide(true)
        }, 500)
      })
    },
    //导入数据
    async execImport(){
      let confirm = 1
      let isCancelConfirm = false
      while (!isCancelConfirm && confirm < 4) {
        const result = await this.$confirm('是否执行数据导入, 第'+confirm+'次确认，总共3次确认哈?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
        });
        if (!result) {
          isCancelConfirm = false
          break
        }
        confirm++
      }
      if (!isCancelConfirm && confirm == 4) {
        this.opType = 2
        this.doImport()
      }
    },
    //删除本次导入临时表数据
    async execRevoke(){
      const result = await this.$confirm('是否删除本次导入临时表数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
      })
      if (!result)  return
      this.opType = 3
      this.doImport()
    },
    //上传成功
    uploadSuccess(file) {
      this.filePath = file.response.data.url
      this.opType = 1
      this.utilMessage.warning('开始导入')
      this.doImport()
      this.$refs.fileHistory.loadFiles()
    },
    //删除成功
    removeSuccess() {
      this.$refs.fileHistory.loadFiles()
      this.importMsg = ''
    },
    //导入临时表或者导入正式表
    doImport() {
      this.utilVue.loadShow(true)
      if (this.opType == 1)  this.importStamp = null
      this.importMsg = '操作中，请稍候'
      const params = {
        importViewKey: this.viewKey,
        filePath: this.filePath,
        importStamp: this.importStamp,
        opType: 4
      }
      this.$ajax.get('/base/matr/importData', { params }).then((response) => {
        this.importMsg = response.msg
        if (response.code == 0) {
          this.utilMessage.success('操作成功')
          this.importStamp = response.data
          //this.fetchData()
        }
        this.utilVue.loadHide()
      }).catch(resp => {
        console.log('resp', resp)
        this.importMsg = resp.msg
      })
    },
    fetchData(){
      // this.$refs.dataview.setQueryWrapper(queryWrapper)
      if (this.$refs.dataview) {
        this.$refs.dataview.setUserParam({importStamp: this.strings.defaultString(this.importStamp,'-1')})
        this.$refs.dataview.fetchData()
      }
      if (this.$refs.fileUpload) {
        this.$refs.fileUpload.clearFiles()
      }
    }
  },

  watch:{
    //参数变化后，进行初始化
    param:{
      handler(newValue, oldValue) {
        if (newValue) {
          this.viewKey = this.param.viewKey
          this.fetchData()
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    //自定义列
    myPropCustomCols(){
      return [
        {
          name: 'importStamp',
          cmode: 'extra',
          title: '时间戳',
          width: 150,
          queryType: 'none',
        },
        {
          name: 'importRemark',
          cmode: 'extra',
          title: '导入说明',
          width: 250,
          queryType: 'none',
          fixed: 'right',
        },
        {
          name: 'importResult',
          cmode: 'before',
          title: '导入结果',
          width: 100,
          queryType: 'select',
          fixed: 'left',
          dict:'import_result',
          sort: 1
        }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 5px;
  }


</style>
